<template>
    <el-dialog
     :before-close="handleClose"
     :visible="show"
     :width="`calc(${width} + 60px)`"
    >
      <div 
        id="container"
        style="padding: 10px; box-sizing: border-box;overflow: hidden;"
        :style="{
          transform: `rotate(${isLeftTurn90 ? -90 : 0 }deg)`,
          'overflow-y': isLeftTurn90 ? 'auto' : ''
        }"
      >
        <div 
          id="main" 
          style="width: 100%; position: relative;overflow: hidden;" 
          :style="{
            padding: `${print_settings.printSetting.topMargin}px ${print_settings.printSetting.leftMargin}px`,
            height: isLeftTurn90 ? width : 'auto',
            width: isLeftTurn90 ? height : 'auto',
          }" 
          v-if="show"
        >
          <template v-for="(pageGoods, pageGoodsIndex) in order_list">
            <div :key="'pageGoods' + pageGoodsIndex" style="width: 100%; position: relative">
            <!-- 标题 -->
            <div 
              v-if="tem_id == 9 && print_settings.fontset" 
              class="header" 
              style="height: 30px; lineheight: 30px;" 
              :style="{
                fontSize: print_settings.fontset.fontSize + 'px',
                fontWeight: print_settings.fontset.bold ? 'bold' : 'none',
                textDecoration: print_settings.fontset.underline
                ? 'underline'
                : 'none',
                fontStyle: print_settings.fontset.italic ? 'italic' : 'none',
                textAlign: print_settings.fontset.textAlign
              }"
            >
              {{ print_settings.page.headerTitle || "" }}
            </div>

            <div v-else class="header" style="font-size: 30px; height: 30px; lineheight: 30px;" :style="{ textAlign: a }">
                {{ print_settings.page.headerTitle || "" }}
            </div>

            <div style="clear: both"></div>
            <!-- 订单信息 -->
            <div style="width: 100%; position: absolute">
              <span 
                v-for="(item, index) in getOrderList"
                :key="index"
                :style="{
                  width:'auto',
                  height:'auto',
                  position: 'absolute',
                  zIndex: '1',
                  left: item.containerStyle.left,
                  top: item.containerStyle.top,
                  ...item.style,
                }"
              >
                <template v-if="item.name === '二维码'">
                  <div id="qrcode"></div>
                </template>
                <template v-else>
                  {{ item.name }}{{ item.isCustom ? "" : ":" }}{{ order[`${item.index - 1}`] }}
                </template>
              </span>
            </div>
            <div style="clear: both"></div>
           <!-- 线段 -->
           <div style="width: 100%; position: absolute">
              <span 
                v-for="(item, index) in getLineList" 
                :key="index"
                style="position: absolute; z-index: 1;" 
                :style="{
                   left: item.containerStyle.left,
                   top: item.containerStyle.top,
                   ...item.style,
                   width: item.containerStyle.width,
                   height: item.containerStyle.height,
                }"
              >
              </span>
            </div>
            <div style="clear: both"></div>
            <!-- 配送单商品信息 -->
            <div 
              class="goods" 
              style="width: 100%; margin: 0; padding: 0; position: relative" 
              :style="{ marginTop: tableHeight + 'px' }" 
              v-if="print_document_type == 'order' && print_settings.printSetting.is_category"
            >
              <!-- 分类 -->
              <table 
                style="
                  margin: 0;
                  margin-bottom: 6px;
                  padding: 0;
                  border-collapse: collapse;
                  border-spacing: 0;
                  border: 1px solid #000;
                  border-bottom: 0;
                  position: relative;
                "
                :style="{ left: tableContainerStyle.left }"
              >
                <tbody>
                  <tr style="height: 25px; line-height: 25px" :style="getTableConfig.style">
                    <td style="border: 1px solid #000; padding: 0 5px">
                      类别
                    </td>
                    <td v-for="(item, index) in category_list" :key="index" style="border: 1px solid #000; padding: 0 5px">
                        {{ item.category_name }}
                    </td>
                  </tr>
                  <tr style="height: 25px; line-height: 1.5" :style="getTableConfig.style">
                    <td style="border: 1px solid #000; padding: 0 5px">
                      商品数
                    </td>
                    <td v-for="(item, index) in category_list" :key="index" style="border: 1px solid #000; padding: 0 5px">
                      {{ item.class }}
                    </td>
                  </tr>
                </tbody>
              </table>
              <!-- 商品 -->
              <table 
                style="
                  width: 100%;
                  margin: 0;
                  padding: 0;
                  border-collapse: collapse;
                  border-spacing: 0;
                  border: 1px solid #000;
                  border-bottom: 0;
                  position: relative;
                "
                :style="{ width: tableContainerStyle.width, left: tableContainerStyle.left }"
              >
                <tbody>
                  <tr :style="{ ...getTableConfig.style, height: '25px' }">
                    <td v-for="(item, index) in getTableConfig.columns" :key="index" :width="item.width" style="border: 1px solid #000;">
                      {{ item.name }}
                    </td>
                  </tr>
                  <template v-for="(goods, index) in pageGoods">
                    <template v-if="democc(goods)">
                      <tr :key="index" :style="{ ...getTableConfig.style, height: `${tableTrHeight}px` }">
                        <td v-for="(father, index) in getTableConfig.columns" :key="index" :width="father.width" style="border: 1px solid #000; border-top: 0">
                          {{ goods[`${father.index - 1}`] }}
                        </td>
                      </tr>
                    </template>
                    <template v-else>
                      <tr :key="index" :style="{ ...getTableConfig.style, height: `${tableTrHeight}px` }">
                        <td style="border: 1px solid #000;border-top: 0;padding-left: 15px;" colspan="30">
                          {{ goods.category_name }}小计：{{ goods.money }}
                        </td>
                      </tr>
                    </template>
                  </template>
                </tbody>
              </table>
            </div>

            <!-- 除配送单外的商品信息 -->
            <div 
              class="goods" 
              style="width: 100%; margin: 0; padding: 0" 
              :style="{ marginTop: tableHeight + 'px' }" 
              v-else
            >
              <table 
                style="
                  width: 100%;
                  margin: 0;
                  padding: 0;
                  border-collapse: collapse;
                  border-spacing: 0;
                  border: 1px solid #000;
                  border-bottom: 0;
                  position: relative;
                "
                :style="{ width: tableContainerStyle.width, left: tableContainerStyle.left }"
              >
                <tbody>
                  <tr :style="{ ...getTableConfig.style, height: '25px' }">
                    <template v-if="tem_id == 9 && print_settings.printSetting.doublePrinting == 1">
                      <td v-for="(two, oindex) in newtablist" :key="oindex" style="border: 1px solid #000;">
                        {{ two.name }}
                      </td>
                      <td v-for="(two, oindex) in newtablist" :key="oindex + '1'" style="border: 1px solid #000">
                        {{ two.name }}
                      </td>
                    </template>
                    <template v-else>
                      <td v-for="(one, oindex) in getTableConfig.columns" :key="oindex" style="border: 1px solid #000"  :width="one.width">
                        {{ one.name }}
                      </td>
                    </template>
                  </tr>
                  <tr v-for="(item, indexs) in pageGoods" :key="indexs" :style="getTableConfig.style">
                    <template v-if="tem_id == 9 && print_settings.printSetting.doublePrinting == 1">
                      <template v-if="Object.keys(pageGoods).length >= (item[0] - pageGoodsIndex * lineNumber) * 2 ">
                        <td 
                          v-for="(father, index) in getTableConfig.columns" 
                          :key="index" 
                          style="border: 1px solid #000; border-top: 0" 
                          :height="tableTrHeight"
                        >
                          <div v-if="showPageHeader">
                            {{
                              pageGoods[
                                (item[0] * 2 -
                                    1 -
                                    1 -
                                    pageGoodsIndex * lineNumber) %
                                lineNumber
                                ] &&
                                pageGoods[
                                (item[0] * 2 -
                                    1 -
                                    1 -
                                    pageGoodsIndex * lineNumber) %
                                lineNumber
                                ][1]
                                ? pageGoods[
                                (item[0] * 2 -
                                    1 -
                                    1 -
                                    pageGoodsIndex * lineNumber) %
                                lineNumber
                                ][`${father.index - 1}`]
                                : ""
                            }}
                          </div>
                          <div v-else>
                            {{
                              pageGoods[
                              item[0] * 2 - 1 - pageGoodsIndex * lineNumber
                              ][1]
                              ? pageGoods[
                              item[0] * 2 - 1 - pageGoodsIndex * lineNumber
                              ][`${father.index - 1}`]
                              : ""
                            }}
                          </div>
                        </td>
                        <td 
                          v-for="(fathers, index) in getTableConfig.columns" 
                          :key="index + '1'" 
                          style="
                            border: 1px solid #000;
                            border-top: 0;
                            height: 30px;
                          "
                        >
                          <div v-if="showPageHeader">
                            {{
                              (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                              lineNumber !=
                              0 &&
                              pageGoods[
                              (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                              lineNumber
                              ] &&
                              pageGoods[
                              (item[0] * 2 - 1 - pageGoodsIndex * lineNumber) %
                              lineNumber
                              ][1]
                              ? pageGoods[
                              (item[0] * 2 -
                                  1 -
                                  pageGoodsIndex * lineNumber) %
                              lineNumber
                              ][`${fathers.index - 1}`]
                              : ""
                            }}
                          </div>
                          <div v-else>
                            {{
                              pageGoods[
                              item[0] * 2 - pageGoodsIndex * lineNumber
                              ][1]
                              ? pageGoods[
                              item[0] * 2 - pageGoodsIndex * lineNumber
                              ][`${fathers.index - 1}`]
                              : ""
                            }}
                          </div>
                        </td>
                      </template>
                    </template>
                    <template v-else>
                      <td 
                        v-for="(its, index) in getTableConfig.columns" 
                        :key="index" 
                        style="border: 1px solid #000; border-top: 0;" 
                        :width="its.width" 
                        :height="tableTrHeight"
                      >
                        {{ item[`${its.index - 1}`] }}
                      </td>
                    </template>
                  </tr>
                </tbody>
              </table>
            </div>

            <div style="clear: both"></div>
            <!-- 合计 -->
            <div class="count">
              <table 
                style="
                  width: 100%;
                  margin: 0;
                  padding: 0;
                  border: 1px solid #000;
                  border-bottom: 0;
                  border-top: 0;
                  border-spacing: 0;
                  border-collapse: collapse;
                  position: relative;
                "
                :style="{ width: tableContainerStyle.width, left: tableContainerStyle.left }"
              >
                <tbody>
                  <tr :style="{ ...getTableConfig.style, height: '25px' }">
                    <td 
                      style="border: 1px solid #000; border-top: 0"
                      v-for="(item, index) in getTableConfig.countList" 
                      :key="index" 
                      :width="item.width" 
                      :style="item.style"
                    >
                      <div v-if="item.index == 4 && showPageHeader && tem_id == 9">
                          {{ item.name }}:{{ pageGoods.total }}
                      </div>
                      <div v-else-if="item.index > 4 && tem_id == 9">
                          {{ item.name }}:{{ all[`${item.index - 2}`] }}
                      </div>
                      <div v-else>
                          {{ item.name }}:{{ all[`${item.index - 1}`] }}
                      </div>
                    </td>
                  </tr>
                </tbody>
              </table>
            </div>
            <!-- 签字信息 -->
            <div class="sign" style="width: 100%; position: absolute; clear: both;left: 0;" :style="{height: signHeight+'px'}">
              <span
                v-for="(item, index) in getSignList"
                :key="index"
                style="position: absolute;overflow: hidden;z-index: 1;letter-spacing: 1px;"
                :style="{
                  left: item.containerStyle.left,
                  top: item.top + 'px',
                  ...item.style,
                  width: 'auto',
                  height: 'auto',
                  lineHeight: 'none'
                }"
              >
                <span v-if="item.isCustom">{{ item.name }}</span>
                <span v-else>{{ item.name | remove }} {{ item.name=='制单员'? $store.getters.name : '' }}</span>
              </span>
            </div>
            <div :style="{height: signHeight+'px'}"></div>
            <div :style="{ marginBottom: topMargin + 'px' }"></div>
            <p v-if="showPageHeader"  style="font-size: 14px; text-align: center;position: absolute;top: 5px;right: 20px;">
              第{{ pageGoodsIndex + 1 }}页，共{{ order_list.length }}页
            </p>
          </div>
          </template>
        </div>
        <!-- <div id="left" v-if="print_settings.printSetting.isLeftTurn90==true">

        </div> -->
      </div>
      <template slot="footer">
        <div class="el-dialog__footer">
          <span class="title-span">注：打印预览可能跟实际效果有点偏差</span>
          <span>
            <el-button @click="handleClose">取 消</el-button>
            <el-button type="primary" @click="onSubmit" v-if="save=='save'">确 定</el-button>
          </span>
        </div>
      </template>
    </el-dialog>
</template>

<script>
import { res } from '../configuration.js';
import QRCode from "qrcodejs2";
export default {
  props:['width', 'height'],
  data() {
    return {
        show: false,
        print_settings: {},
        main_settings: [],
        // 打印机配置信息
        print_set_info: [],
        tableHeight: 0, // 表格距离上面的外边距
        signHeight: 0, // 距离表格的最大高度
        category_list: [], //分类
        sortgoods: [],
        // 是否分页打印
        lineNumber: 0,
        tableTrHeight: 25,
        showPageHeader: false,
        tem_id: "",
        newtablist: [],
        total: "",
        save:''
    };
  },
  computed: {
    isLeftTurn90() {
      return (this.print_settings.printSetting || {}).isLeftTurn90;
    },
    // 订单信息
    getOrderList({ main_settings }) {
      return main_settings.filter(item => item.type == "inputCheck" || item.type == "input");
    },
    // 线段信息
    getLineList({ main_settings }) {
      return main_settings.filter(item => item.type == "line");
    },
    // 签字信息
    getSignList({ main_settings }) {
      return main_settings.filter(item => item.type == "sign");
    },
    // 表格信息
    getTableConfig({ main_settings }) {
      return main_settings.find(item => item.type === "table");
    },
    // 表格样式
    tableContainerStyle({ getTableConfig }) {
      return getTableConfig.containerStyle || {};
    },
  },
  created() {},
  filters: {
    remove: function (data) {
      if (data.indexOf("：") != -1 || data.indexOf(":") != -1) {
        return data;
      } else {
        return data + ":";
      }
    }
  },
  methods: {
    onSubmit(){
      this.$emit('save');
    },
    democc(data) {
      if (data.category_name) {
        return false;
      } else {
        return true;
      }
    },
    handleClose(){
        this.show = false
    },
    open(data){
        this.show = true;
        this.save = data.save;
        this.all = res.all;
        this.print_document_type = data.type;
        this.main_settings = JSON.parse(data.main_settings);
        this.print_settings = JSON.parse(data.print_settings);
        this.lineNumber = this.print_settings.printSetting.lineNumber || 10;
        this.tableTrHeight = this.print_settings.printSetting.tableTrHeight || 25;
        this.showPageHeader = this.print_settings.printSetting.showPageHeader;
        let topMargin = this.print_settings.printSetting.topMargin;
        this.topMargin = Number(topMargin) + 40;
        this.order = res.order;
        this.order_list = [];
        this.tem_id = data.tem_id;
        if (data.type == "order" && this.print_settings.printSetting.is_category) {
          let arr = [];
          res.order_list1.map(e => {
            arr.push({
              category_name: e.category_name,
              class: e.class,
              money: e.money
            });
          });
          this.category_list = arr;
          this.order_list = this.handleCategory(res.order_list1);
        } else {
          if (
            this.tem_id == 9 &&
            this.print_settings.printSetting.doublePrinting == 1
          ) {
            this.newtablist = this.main_settings.find(item => item.type == 'table').columns
            let len = Object.keys(res.order_list).length;

            if (this.showPageHeader == true) {
              //开启双排和分页
              if (len % 2 == 0) {
                this.order_list = this.group(
                  res.order_list,
                  this.lineNumber
                );
              } else {
                let arr = res.order_list;
                let newlist = arr[1];
                const arr2 = new Array(newlist.length).fill(null);
                arr2[0] = len + 1;
                let key = len + 1;
                let value = arr2;
                arr[key] = value;
                this.order_list = this.group(
                  res.order_list,
                  this.lineNumber
                );
              }
            } else {
              //只开启双排
              if (len % 2 == 0) {
                this.order_list = this.group(
                  res.order_list,
                  this.lineNumber
                );
              } else {
                let arr = res.order_list;
                let newlist = arr[1];
                const arr2 = new Array(newlist.length).fill(null);
                arr2[0] = len + 1;
                let key = len + 1;
                let value = arr2;
                arr[key] = value;
                this.order_list = this.group(
                  res.order_list,
                  this.lineNumber
                );
              }
            }
          } else {
            this.order_list = this.group(res.order_list, this.lineNumber);
          }
        }
        this.show = true;

        this.print_set_info.map(item => {
          if (item.type == res.tem_id) {
            this.print_settings.print_mark = item.print_index;
          }
        });
        let arr = []
        this.main_settings.forEach(item=>{
          if(item.type=='sign'){
            arr.push(item.top)
            this.signHeight = arr.reduce((a, b) => Math.max(a, b));
          }else if(item.type=='table'){
            this.tableHeight = parseInt(item.containerStyle.top)
          }
        });
        this.$nextTick(async () => {
          try {
            await this.generateQRCode("https://new.caidj.net.cn/cmp#/", 80, 80);  // 如果此处报错，捕获异常
          } catch (error) {
            console.error('二维码生成失败:', error);  // 可以打印错误信息或者进行其他处理
          }
        });
    },
    // 生成二维码
    generateQRCode(url, width, height) {
      return new Promise((resolve, reject) => {
        let qrcode = new QRCode("qrcode", {
          text: url,
          width: width,
          height: height,
        });
        // 等待100毫秒以确保二维码已经生成
        setTimeout(() => {
          resolve();
        }, 100);
      });
    },
    // 处理分类数据
    handleCategory(array) {
      let newArray = [];
      array.map(e => {
        let values = Object.values(e.list) ? Object.values(e.list) : [];
        values.map(async i => await newArray.push(i));
        let obj = {
          category_name: e.category_name,
          class: e.class,
          money: e.money
        };
        newArray.push(obj);
      });
      return this.group(newArray, this.lineNumber);
    },
    // 数组分割
    group(array, subGroupLength) {
      let index = 0;
      let newArray = [];
      let suLength = Number(subGroupLength);
      if (this.showPageHeader) {
        if (Array.isArray(array)) {
          while (index < array.length) {
            newArray.push(array.slice(index, (index += suLength)));
          }
        } else {
          let arr = Object.values(array) ? Object.values(array) : [];
          while (index < arr.length) {
            newArray.push(arr.slice(index, (index += suLength)));
          }
        }
      } else {
        newArray = [array];
      }
      if (this.showPageHeader && this.tem_id == 9) {
        newArray.map(e => {
          e.total = 0;
          let total = 0;
          e.map(c => {
            total += Number(c[9]) || 0;
          });
          e.total = this.$toFixed(total);
        });
      }
      return newArray;
    },
  },
};
</script>
<style lang="scss" scoped>
.title-span{
  color: red;
}
/deep/.el-dialog__footer {
  width: 100%;
  display: flex;
  justify-content: space-between;
  align-items: center;
}
/deep/.el-dialog__body{
  padding-top: 0;
}
</style>
